<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    label-width="100px"
    v-loading="formLoading"
  >
    <el-descriptions :column="1"
                     style="background: white; padding: 10px 10px 0 10px; margin-bottom: 10px;">
      <el-descriptions-item min-width="60">
        <template #label>
          <span style="font-size: 16px; font-weight: bold">快递状态</span>
        </template>
        <el-tag type="danger" v-if="formData.auditStatus === 0">未处理</el-tag>
        <el-tag type="success" v-else-if="formData.auditStatus === 1">已出单</el-tag>
        <el-tag type="info" v-else>已取消</el-tag>
      </el-descriptions-item>
    </el-descriptions>
    <el-descriptions :column="1" style="background: white; padding: 10px 10px 0 10px; margin-bottom: 10px;">
      <el-descriptions-item min-width="60">
        <template #label>
          <span style="font-size: 16px; font-weight: bold">下单人信息</span>
        </template>
        <el-descriptions :column="3" style="background: white; padding: 10px 10px 0 10px; margin-bottom: 10px;">
          <el-descriptions-item label="用户ID" min-width="60">
            {{ formData.userId }}
          </el-descriptions-item>
          <el-descriptions-item label="昵称" min-width="60">
            {{ formData.nickname }}
          </el-descriptions-item>
          <el-descriptions-item label="手机号" min-width="60">
            {{ formData.mobile }}
          </el-descriptions-item>
        </el-descriptions>
      </el-descriptions-item>
    </el-descriptions>
    <el-descriptions :column="1" style="background: white; padding: 10px 10px 0 10px; margin-bottom: 10px;">
      <el-descriptions-item min-width="60">
        <template #label>
          <span style="font-size: 16px; font-weight: bold">收件国家</span>
        </template>
        <el-descriptions :column="3" style="background: white; padding: 10px 10px 0 10px">
          <el-descriptions-item min-width="60">
            <el-form-item label="收件国家" prop="country">
              <el-select
                :disabled="globalAuditStatus != 0"
                v-model="formData.country"
                @change="formData.shippingType = undefined"
                placeholder="请选择收件国家"
                clearable
                class="!w-240px"
              >
                <el-option label="韩国" value="韩国"/>
                <el-option label="美国" value="美国"/>
                <el-option label="孟加拉" value="孟加拉"/>
                <el-option label="缅甸" value="缅甸"/>
                <el-option label="柬埔寨" value="柬埔寨"/>
                <el-option label="越南" value="越南"/>
                <el-option label="印度尼西亚" value="印度尼西亚"/>
                <el-option label="其他" value="其他"/>
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item min-width="60">
            <el-form-item label="运输方式" prop="shippingType">
              <el-select
                :disabled="globalAuditStatus != 0"
                v-model="formData.shippingType"
                placeholder="请选择运输方式"
                clearable
                class="!w-240px"
              >
                <el-option v-if="formData.country != '缅甸' && formData.country != '柬埔寨'" label="空运" value="空运"/>
                <el-option v-if="formData.country === '缅甸' || formData.country === '柬埔寨' || formData.country === '越南'" label="陆运" value="陆运"/>
                <el-option v-if="formData.country === '韩国' || formData.country === '其它'" label="海运" value="海运"/>
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item min-width="60">
            <el-form-item label="是否报关" prop="customsFiling">
              <el-radio-group :disabled="globalAuditStatus != 0" v-model="formData.customsFiling">
                <el-radio :value="0">不报关</el-radio>
                <el-radio :value="1">报关</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-descriptions-item>
    </el-descriptions>
    <el-descriptions :column="1" style="background: white; padding: 10px 10px 0 10px; margin-bottom: 10px;">
      <el-descriptions-item min-width="60">
        <template #label>
          <span style="font-size: 16px; font-weight: bold">寄件方信息</span>
        </template>
        <el-descriptions :column="3" style="background: white; padding: 10px 10px 0 10px">
          <el-descriptions-item min-width="60">
            <el-form-item label="公司名称" prop="sendCompany">
              <el-input :disabled="globalAuditStatus != 0" v-model="formData.sendCompany" placeholder="请输入寄件人公司名称"/>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item min-width="60">
            <el-form-item label="所属部门" prop="sendDept">
              <el-input :disabled="globalAuditStatus != 0" v-model="formData.sendDept" placeholder="请输入寄件人所属部门"/>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item min-width="60">
            <el-form-item label="姓名" prop="sendName">
              <el-input :disabled="globalAuditStatus != 0" v-model="formData.sendName" placeholder="请输入寄件人姓名"/>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item min-width="60">
            <el-form-item label="手机号" prop="sendMobile">
              <el-input :disabled="globalAuditStatus != 0" v-model="formData.sendMobile" placeholder="请输入寄件人手机号"/>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item min-width="60">
            <el-form-item label="详细地址" prop="sendAddress">
              <el-input :disabled="globalAuditStatus != 0" v-model="formData.sendAddress" placeholder="请输入寄件人详细地址"/>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-descriptions-item>
    </el-descriptions>
    <el-descriptions :column="1" style="background: white; padding: 10px 10px 0 10px; margin-bottom: 10px;">
      <el-descriptions-item min-width="60">
        <template #label>
          <span style="font-size: 16px; font-weight: bold">收件方信息</span>
        </template>
        <el-descriptions :column="3" style="background: white; padding: 10px 10px 0 10px">
          <el-descriptions-item min-width="60">
            <el-form-item label="公司名称" prop="recipientsCompany">
              <el-input :disabled="globalAuditStatus != 0" v-model="formData.recipientsCompany" placeholder="请输入收件人公司名称"/>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item min-width="60">
            <el-form-item label="所属部门" prop="recipientsDept">
              <el-input :disabled="globalAuditStatus != 0" v-model="formData.recipientsDept" placeholder="请输入收件人所属部门"/>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item min-width="60">
            <el-form-item label="姓名" prop="recipientsName">
              <el-input :disabled="globalAuditStatus != 0" v-model="formData.recipientsName" placeholder="请输入收件人姓名"/>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item min-width="60">
            <el-form-item label="手机号" prop="recipientsMobile">
              <el-input :disabled="globalAuditStatus != 0" v-model="formData.recipientsMobile" placeholder="请输入收件人手机号"/>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item min-width="60">
            <el-form-item label="详细地址" prop="recipientsAddress">
              <el-input :disabled="globalAuditStatus != 0" v-model="formData.recipientsAddress" placeholder="请输入收件人详细地址"/>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-descriptions-item>
    </el-descriptions>
    <el-descriptions :column="1" style="background: white; padding: 10px 10px 0 10px; margin-bottom: 10px;">
      <el-descriptions-item min-width="60">
        <template #label>
          <span style="font-size: 16px; font-weight: bold">结款方式</span>
        </template>
        <el-descriptions :column="2" style="background: white; padding: 10px 10px 0 10px">
          <el-descriptions-item min-width="60">
            <el-form-item label="结款方式" prop="payMethod">
              <el-radio-group :disabled="globalAuditStatus != 0" v-model="formData.payMethod">
                <el-radio :value="0">寄付</el-radio>
                <el-radio :value="1">到付</el-radio>
                <el-radio :value="2">第三方结款</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-descriptions-item>
          <el-descriptions-item min-width="60">
            <el-form-item label="客户账号" prop="customerAccount">
              <el-input :disabled="globalAuditStatus != 0" v-model="formData.customerAccount" placeholder="请输入客户账号"/>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-descriptions-item>
    </el-descriptions>
    <el-descriptions :column="1" style="background: white; padding: 10px 10px 0 10px; margin-bottom: 10px;">
      <el-descriptions-item min-width="60">
        <template #label>
          <span style="font-size: 16px; font-weight: bold">货物信息</span>
        </template>
        <el-descriptions :column="1" style="background: white; padding: 10px 10px 0 10px">
          <el-descriptions-item min-width="60">
            <el-form-item label="发票号" prop="invoiceNum">
              <el-input :disabled="globalAuditStatus != 0" v-model="formData.invoiceNum" placeholder="请输入发票号"/>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
        <el-descriptions v-for="(good, i) in formData.goods" :key="i" :column="1" style="margin-left: 10px">
          <el-descriptions-item min-width="60">
            <template #label>
              <span style="font-size: 16px; font-weight: bold">货物 {{i + 1}}</span>
            </template>
            <el-descriptions :column="3" style="background: white; padding: 10px 10px 0 10px">
              <el-descriptions-item min-width="60">
                <el-form-item label="名称" prop="name">
                  <el-input :disabled="globalAuditStatus != 0" v-model="good.name" placeholder="请输入货物名称"/>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item min-width="60">
                <el-form-item label="单价" prop="unitPrice">
                  <el-input :disabled="globalAuditStatus != 0" v-model="good.unitPrice" placeholder="请输入货物单价"/>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item min-width="60">
                <el-form-item label="数量" prop="num">
                  <el-input :disabled="globalAuditStatus != 0" v-model="good.num" placeholder="请输入货物数量"/>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item min-width="60">
                <el-form-item label="货物总价格" prop="totalPrice">
                  <el-input :disabled="globalAuditStatus != 0" v-model="good.totalPrice" placeholder="请输入货物总价格"/>
                </el-form-item>
              </el-descriptions-item>
            </el-descriptions>
          </el-descriptions-item>
        </el-descriptions>
      </el-descriptions-item>
    </el-descriptions>
    <el-descriptions :column="1" style="background: white; padding: 10px 10px 0 10px; margin-bottom: 10px;">
      <el-descriptions-item min-width="60">
        <template #label>
          <span style="font-size: 16px; font-weight: bold">发货方式</span>
        </template>
        <el-descriptions :column="1" style="background: white; padding: 10px 10px 0 10px">
          <el-descriptions-item min-width="60">
            <el-form-item label-width="130" label="快递单号/上门取件" prop="expressageOrder">
              <el-input :disabled="globalAuditStatus != 0" v-model="formData.expressageOrder" placeholder="请输入快递单号/上门取件"/>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-descriptions-item>
    </el-descriptions>
    <el-descriptions :column="1" style="background: white; padding: 10px 10px 0 10px; margin-bottom: 10px;">
      <el-descriptions-item min-width="60">
        <template #label>
          <span style="font-size: 16px; font-weight: bold">寄件信息</span>
        </template>
        <el-descriptions :column="2" style="background: white; padding: 10px 10px 0 10px">
          <el-descriptions-item label="运单号" min-width="60">
            {{formData.orderNo}}
          </el-descriptions-item>
          <el-descriptions-item label="下单时间" min-width="60">
            {{formData.createTime}}
          </el-descriptions-item>
        </el-descriptions>
      </el-descriptions-item>
    </el-descriptions>
    <el-descriptions :column="1" style="background: white; padding: 10px 10px 0 10px; margin-bottom: 10px;">
      <el-descriptions-item min-width="60">
        <template #label>
          <span style="font-size: 16px; font-weight: bold">审核信息</span>
        </template>
        <el-descriptions :column="1" style="background: white; padding: 10px 10px 0 10px">
          <el-descriptions-item min-width="60">
            <el-form-item label="审核状态" prop="auditStatus">
              <el-radio-group :disabled="globalAuditStatus != 0" v-model="formData.auditStatus">
                <el-radio :value="0">未处理</el-radio>
                <el-radio :value="1">出单</el-radio>
                <el-radio :value="2">取消</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
        <el-descriptions v-if="formData.auditStatus != 0 && formData.auditDatetime" :column="1" style="margin-left: 40px">
          <el-descriptions-item min-width="60">
            <template #label>
              <span v-if="formData.auditStatus === 1">出单时间</span>
              <span v-else>取消时间</span>
            </template>
            {{formData.auditDatetime}}
          </el-descriptions-item>
        </el-descriptions>
        <el-descriptions v-if="formData.auditStatus != 0 && formData.auditAdminUserId" :column="1" style="margin-left: 40px">
          <el-descriptions-item label="审核人" min-width="60">
            ID：{{formData.auditAdminUserId}}，
            用户名：{{formData.auditAdminUsername ? formData.auditAdminUsername : '-'}}，
            手机号：{{formData.auditAdminUserMobile ? formData.auditAdminUserMobile : '-'}}
          </el-descriptions-item>
        </el-descriptions>
      </el-descriptions-item>
    </el-descriptions>
    <el-descriptions :column="1" style="background: white; padding: 10px 10px 0 10px; margin-bottom: 10px;">
      <el-descriptions-item min-width="60">
        <el-button @click="returnList">返回列表</el-button>
        <el-button v-if="globalAuditStatus === 0" @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
        <el-button v-if="globalAuditStatus === 1" @click="downloadFile(1, [formData.id])" type="primary" :disabled="formLoading">下载Pdf面单</el-button>
        <el-button v-if="globalAuditStatus === 1" @click="downloadFile(2, [formData.id])" type="success" :disabled="formLoading">下载Pdf发票</el-button>
        <el-button v-if="globalAuditStatus === 1" @click="downloadFile(3, [formData.id])" type="success" :disabled="formLoading">下载Excel发票</el-button>
      </el-descriptions-item>
    </el-descriptions>
  </el-form>
</template>
<script setup lang="ts">
import {ExpressageApi, Expressage} from '@/api/business/expressage'
import {useRoute, useRouter} from "vue-router";
import {DICT_TYPE, getIntDictOptions} from "@/utils/dict";
import {formatDate} from "@/utils/formatTime";
import {array} from "vue-types";

/** 寄件信息 表单 */
defineOptions({name: 'ExpressageForm'})

const route = useRoute() // 路由
const router = useRouter() // 路由

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  orderNo: undefined,
  createTime: undefined,
  userId: undefined,
  nickname: undefined,
  mobile: undefined,
  country: undefined,
  shippingType: undefined,
  customsFiling: undefined,
  sendName: undefined,
  sendMobile: undefined,
  sendAddress: undefined,
  sendCompany: undefined,
  sendDept: undefined,
  recipientsName: undefined,
  recipientsMobile: undefined,
  recipientsAddress: undefined,
  recipientsCompany: undefined,
  recipientsDept: undefined,
  payMethod: undefined,
  customerAccount: undefined,
  invoiceNum: undefined,
  expressageOrder: undefined,
  auditStatus: undefined,
  auditDatetime: undefined,
  auditAdminUserId: undefined,
  goods: [],
})
const formRules = reactive({
  country: [{required: true, message: '收件国家不能为空', trigger: 'blur'}],
  shippingType: [{required: true, message: '运输方式不能为空', trigger: 'blur'}],
  sendName: [{required: true, message: '寄件人姓名不能为空', trigger: 'blur'}],
  sendMobile: [{required: true, message: '寄件人手机号不能为空', trigger: 'blur'}],
  sendAddress: [{required: true, message: '寄件人详细地址不能为空', trigger: 'blur'}],
  sendCompany: [{required: true, message: '寄件人公司名称不能为空', trigger: 'blur'}],
  recipientsName: [{required: true, message: '收件人姓名不能为空', trigger: 'blur'}],
  recipientsMobile: [{required: true, message: '收件人手机号不能为空', trigger: 'blur'}],
  recipientsAddress: [{required: true, message: '收件人详细地址不能为空', trigger: 'blur'}],
  recipientsCompany: [{required: true, message: '收件人公司名称不能为空', trigger: 'blur'}],
  payMethod: [{
    required: true,
    message: '付款方式不能为空',
    trigger: 'blur'
  }],
  auditStatus: [{
    required: true,
    message: '审核状态不能为空',
    trigger: 'blur'
  }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const returnList = async () => {
  router.push({
    name: 'ExpressageList'
  })
}

let globalAuditStatus = ref(0)

/** 打开弹窗 */
const open = async (id?: number) => {
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ExpressageApi.getExpressage(id)
      globalAuditStatus.value = formData.value.auditStatus
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 下载面单 */
const downloadFile = async (type: number, ids: array) => {
  let fileUrl = await ExpressageApi.downloadExpressage(type, {ids: ids})
  const a = document.createElement('a')
  a.href = fileUrl
  a.download = formData.value.orderNo + '.xlsx'
  a.click()
}


/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as Expressage

    if (data.auditStatus === 1){
      // 二次确认
      await message.confirm('已核对信息填写无误，是否确认出单？', '确认出单')
    }else if (data.auditStatus === 2){
      // 二次确认
      await message.confirm('部分信息填写有误，是否确认取消出单？', '取消出单')
    }

    await ExpressageApi.updateExpressage(data)
    message.success(t('common.updateSuccess'))

    await open(route.query.id as any)

    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    orderNo: undefined,
    createTime: undefined,
    userId: undefined,
    country: undefined,
    shippingType: undefined,
    customsFiling: undefined,
    sendName: undefined,
    sendMobile: undefined,
    sendAddress: undefined,
    sendCompany: undefined,
    sendDept: undefined,
    recipientsName: undefined,
    recipientsMobile: undefined,
    recipientsAddress: undefined,
    recipientsCompany: undefined,
    recipientsDept: undefined,
    payMethod: undefined,
    customerAccount: undefined,
    invoiceNum: undefined,
    expressageOrder: undefined,
    auditStatus: undefined,
    auditDatetime: undefined,
    auditAdminUserId: undefined,
    goods: [],
  }
  formRef.value?.resetFields()
}

/** 初始化 **/
onMounted(() => {
  if (!route.query.id) {
    message.error('ID 不存在，无法查看快递详情')
    return
  }

  // 从路由参数中获取 ID
  open(route.query.id as any)
})
</script>
